<template>
  <div class="menu-container">
    <table-list
      :columns="columns"
      :data-source="menuList"
      :loading="loading"
      :pagination="false"
      :show-search="true"
      :actions="actions"
      @action="handleAction"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'type'">
          <a-tag :color="record.type === 'menu' ? 'blue' : 'green'">
            {{ record.type === 'menu' ? "菜单" : "按钮" }}
          </a-tag>
        </template>
        <template v-if="column.key === 'hidden'">
          <a-tag :color="record.hidden === 1 ? 'red' : 'green'">
            {{ record.hidden === 1 ? "隐藏" : "显示" }}
          </a-tag>
        </template>
        <template v-if="column.key === 'always_show'">
          <a-tag :color="record.always_show === 1 ? 'blue' : 'orange'">
            {{ record.always_show === 1 ? "是" : "否" }}
          </a-tag>
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a @click="handleEdit(record)" v-permission="'system:menu:edit'">编辑</a>
            <a-divider type="vertical" />
            <a @click="handleAddChild(record)" v-permission="'system:menu:add'">添加子菜单</a>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除此菜单吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="handleDelete(record)"
            >
              <a class="danger-text" v-permission="'system:menu:delete'">删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>

      <template #extraContent>
        <!-- 菜单表单弹窗 -->
        <a-modal
          v-model:open="modalVisible"
          :title="modalTitle"
          @ok="handleFormSubmit"
          @cancel="resetForm"
          :confirm-loading="submitLoading"
        >
          <a-form ref="formRef" :model="formState" :rules="formRules" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
            <a-form-item label="上级菜单" name="parent_id">
              <a-tree-select
                v-model:value="formState.parent_id"
                :tree-data="treeMenuList"
                placeholder="请选择上级菜单"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                allow-clear
                tree-default-expand-all
              />
            </a-form-item>
            <a-form-item label="菜单类型" name="type">
              <a-radio-group v-model:value="formState.type">
                <a-radio value="menu">菜单</a-radio>
                <a-radio value="button">按钮</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="菜单标题" name="title" required>
              <a-input v-model:value="formState.title" placeholder="请输入菜单标题" />
            </a-form-item>
            <a-form-item label="菜单名称" name="name" required>
              <a-input v-model:value="formState.name" placeholder="请输入菜单名称" />
            </a-form-item>
            <template v-if="formState.type === 'menu'">
              <a-form-item label="菜单路径" name="path" required>
                <a-input v-model:value="formState.path" placeholder="请输入菜单路径" />
              </a-form-item>
              <a-form-item label="组件路径" name="component">
                <a-input v-model:value="formState.component" placeholder="请输入组件路径" />
              </a-form-item>
              <a-form-item label="重定向" name="redirect">
                <a-input v-model:value="formState.redirect" placeholder="请输入重定向路径" />
              </a-form-item>
              <a-form-item label="菜单图标" name="icon">
                <a-input v-model:value="formState.icon" placeholder="请输入菜单图标" />
              </a-form-item>
              <a-form-item label="是否隐藏" name="hidden">
                <a-switch v-model:checked="formState.hidden" :checked-value="1" :unCheckedValue="0" />
              </a-form-item>
              <a-form-item label="始终显示" name="always_show">
                <a-switch v-model:checked="formState.always_show" :checked-value="1" :unCheckedValue="0" />
              </a-form-item>
              <a-form-item label="是否缓存" name="keep_alive">
                <a-switch v-model:checked="formState.keep_alive" :checked-value="1" :unCheckedValue="0" />
              </a-form-item>
            </template>
            <!-- <template v-if="formState.type === 'button'"> -->
              <a-form-item label="权限标识" name="permission_code">
                <a-input v-model:value="formState.permission_code" placeholder="请输入权限标识" />
              </a-form-item>
            <!-- </template> -->
            <a-form-item label="排序" name="sort">
              <a-input-number v-model:value="formState.sort" :min="0" style="width: 100%" />
            </a-form-item>
          </a-form>
        </a-modal>
      </template>
    </table-list>
  </div>
</template>

<script setup>
import { getMenuList, addMenu, updateMenu, deleteMenu } from "@/request/api";
import { userPermissionStore } from "@/stores/user";
import { PlusOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { onMounted, reactive, ref, computed, watch } from "vue";
import TableList from "@/components/TableList.vue";
import { useTableList } from "@/hooks/useTableList";

const store = userPermissionStore();

// 默认表单数据
const defaultForm = {
  id: null,
  parent_id: 0,
  title: "",
  name: "",
  path: "",
  component: "",
  redirect: "",
  icon: "",
  type: "menu",
  permission_code: "",
  sort: 0,
  hidden: 0,
  always_show: 0,
  keep_alive: 0
};

// 表单规则
const formRules = computed(() => {
  const baseRules = {
    title: [{ required: true, message: "请输入菜单标题" }],
    name: [{ required: true, message: "请输入菜单名称" }],
  };
  
  if (formState.type === 'menu') {
    return {
      ...baseRules,
      path: [{ required: true, message: "请输入菜单路径" }]
    };
  } else {
    return {
      ...baseRules,
      permission_code: [{ required: true, message: "请输入权限标识" }]
    };
  }
});

// 使用组合式函数
const {
  dataList:menuList,
  loading,
  formState,
  formRef,
  queryParams,
  modalVisible,
  submitLoading,
  modalTitle,

  handleAdd,
  handleEdit,
  handleDelete,
  handleFormSubmit,
  resetForm,
  handleAction
} = useTableList({
  fetchListApi: getMenuList,
  addApi: addMenu,
  updateApi: updateMenu,
  deleteApi: deleteMenu,
  defaultForm,
  formRules,
  hasPagination: false,
});

// 监听表单类型变化，重置验证规则
watch(() => formState.type, () => {
  formRef.value && formRef.value.validate();
});

// 菜单列表转树形结构用于下拉选择
const treeMenuList = computed(() => {
  const convertToTreeData = (list, parentId = 0) => {
    return list
      .filter((item) => item.parent_id === parentId && item.type === 'menu')
      .map((item) => ({
        value: item.id,
        title: item.title,
        children: convertToTreeData(list, item.id)
      }));
  };

  return [{ value: 0, title: "顶级菜单" }, ...convertToTreeData([...menuList.value])];
});

// 表格列定义
const columns = [
  { title: "菜单名称", dataIndex: "title", key: "title" },
  { title: "菜单类型", dataIndex: "type", key: "type" },
  { title: "路由名称", dataIndex: "name", key: "name" },
  { title: "路由路径", dataIndex: "path", key: "path" },
  { title: "组件路径", dataIndex: "component", key: "component" },
  { title: "权限标识", dataIndex: "permission_code", key: "permission_code" },
  { title: "图标", dataIndex: "icon", key: "icon" },
  { title: "排序", dataIndex: "sort", key: "sort" },
  { title: "是否隐藏", dataIndex: "hidden", key: "hidden" },
  { title: "始终显示", dataIndex: "always_show", key: "always_show" },
  { title: "操作", key: "action", fixed: "right", width: 250 }
];

// 操作按钮配置
const actions = [
  {
    label: "新增菜单",
    props: {
      type: "primary"
    },
    icon: PlusOutlined,
    handler: handleAdd,
    key: "add",
    permission: "system:menu:add"
  }
];

// 添加子菜单
const handleAddChild = (record) => {
  resetForm();
  formState.parent_id = record.id;
  modalVisible.value = true;
};

onMounted(() => {
  // loadMenuList();
});
</script>

<style scoped>
.menu-container {
  padding: 20px;
}
.danger-text {
  color: #ff4d4f;
}
</style>
